package com.lap.framework.generator.domain.template;

import com.lap.framework.generator.domain.FileModel;
import com.lap.framework.generator.domain.TemplateModel;
import com.lap.framework.generator.infra.persistence.TemplateEngine;
import com.lap.framework.generator.shared.exception.GeneratorException;
import com.lap.framework.generator.shared.tool.FileUtil;
import com.lap.framework.generator.shared.tool.PackUtil;
import freemarker.template.TemplateException;
import java.io.IOException;
import lombok.experimental.UtilityClass;

@UtilityClass
public class TemplateGenerator {

  /**
   * 通用文件生成方法
   *
   * @param model 模板模型数据
   * @param packageSegments 包路径分段 (示例：["adapter", "driving", "persistence", "repository"])
   * @param fileSegments 文件分段 (不含扩展名)
   * @param ext 文件扩展名
   * @param templatePath 模板文件路径
   * @return 文件模型
   */
  public static FileModel generateFile(
      TemplateModel model,
      String[] packageSegments,
      String[] fileSegments,
      String ext,
      String templatePath) {

    validateParams(model, packageSegments, fileSegments, templatePath);

    try {
      TemplateEngine engine = new TemplateEngine();
      String path = PackUtil.pack2Path(packageSegments);
      String content = engine.processTemplate(templatePath, model);
      String fullFileName = FileUtil.resolveFile(ext, fileSegments);

      return FileModel.builder().path(path).fileName(fullFileName).content(content).build();
    } catch (IOException | TemplateException e) {
      throw new GeneratorException("模板生成失败: " + templatePath, e);
    }
  }

  private static void validateParams(
      TemplateModel model, String[] segments, String[] fileSegments, String templatePath) {
    if (model == null) throw new IllegalArgumentException("模型数据不能为空");
    if (segments == null || segments.length == 0) throw new IllegalArgumentException("包路径分段无效");
    if (fileSegments == null || fileSegments.length == 0)
      throw new IllegalArgumentException("文件名分段无效");
    if (templatePath == null || !templatePath.endsWith(".ftl"))
      throw new IllegalArgumentException("模板路径格式错误");
  }
}
